package com.lufan.util;

import com.lufan.constant.DefaultConstants;
import com.lufan.factory.HttpClientFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

/**
 * 下载工具类
 */
public class DownloadUtil {

    public static String parseBvid(String url) {
        if (!url.startsWith("https://www.bilibili.com")) {
            return null;
        }
        String[] split = url.split("/");
        String bvid=split[4];
        if(!bvid.startsWith("BV")){
            return null;
        }
        if(bvid.contains("?")){
            bvid = bvid.substring(0,bvid.indexOf("?"));
        }
        return bvid;
    }

//    public static void downloadVideo(boolean isVideo,String videoUrl, String savePath) throws Exception {
//        HttpClient client = HttpClientFactory.getHttpClient();
//        HttpRequest request = HttpRequest.newBuilder()
//                .uri(URI.create(videoUrl))
//                .header("user-Agent", DefaultConstants.headers.get("User-Agent"))
//                .header("referer", DefaultConstants.headers.get("Referer"))
//                .header("cookie", DefaultConstants.headers.get("Cookie"))
//                .build();
//        HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
//
//        try (InputStream is = response.body();
//             ReadableByteChannel rbc = Channels.newChannel(is);
//             RandomAccessFile file = new RandomAccessFile(savePath, "rw")) {
//
//            long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(0L);
//            long downloadedBytes = 0;
//
//            // 第一步：独立输出文件路径（带换行）
//            String fileType = isVideo ? "视频" : "音频";
//            System.out.println("当前下载" + fileType + ": " + savePath);
//
//            // 第二步：初始化进度条（单独一行）
//            System.out.print("下载进度:  0.0%");
//            System.out.flush();
//
//            while (true) {
//                long bytesRead = file.getChannel().transferFrom(rbc, downloadedBytes, BUFFER_SIZE);
//                if (bytesRead <= 0) break;
//                downloadedBytes += bytesRead;
//
//                double progress = (totalBytes > 0)
//                        ? (downloadedBytes * 100.0) / totalBytes
//                        : (downloadedBytes * 100.0) / (downloadedBytes + bytesRead + 1);
//
//                // 第三步：仅更新进度条（保持单行）
//                System.out.printf("\r下载进度: %5.1f%%", progress);
//                System.out.flush();
//            }
//
//            // 第四步：完成提示（换行显示）
//            System.out.println("\n下载完成: 100.0% 保存路径: " + savePath);
//
//        } catch (IOException e) {
//            System.out.println("\n下载中断: " + e.getMessage());
//        }
//    }
}
